package org.linphone.utils;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import org.linphone.LinphoneManager;
import org.linphone.LinphoneService;
import org.linphone.core.Call;
import org.linphone.core.Core;

public class LinphoneHelper {

    private static class LinphoneHolder {
        private static LinphoneHelper holder = new LinphoneHelper();
    }

    public static LinphoneHelper getInstance() {
        return LinphoneHolder.holder;
    }


    //先判断是否登录，再调用这个方法
    public void startLinphoneService(Context context) {
        Intent intent = new Intent(context, LinphoneService.class);
        context.startService(intent);
    }

    // 登录帐号
    public void register(String userId, String password, String serverUrl) {
        if (LinphoneService.isReady()) {
            LinphoneService.instance().startLinphoneAuthInfo(userId, password, serverUrl);
        }

    }

    // 拨打电话
    public void call( String callName, boolean isVideoEnable) {
        if (LinphoneService.isReady()) {
            // 开始拨打电话
            LinphoneManager.getInstance().newOutgoingCall(callName, isVideoEnable);
        }
    }

    public void unRegister() {
        if (LinphoneService.isReady()) {
            LinphoneService.instance().unRegisterAuthInfo();
        }
    }

    // 关闭voip
    public void stopVoip(Context context) {
        Intent intent = new Intent(context, LinphoneService.class);
        context.stopService(intent);
    }



    public boolean isTalk(Call call){
        return TextUtils.equals(LinphoneService.talkRoom,call.getRemoteAddress().getUsername());
    }

    /**
     * 恢复对讲
     */
    public void resumeTalkCall(String talkRoom) {
        Call call = lookTalkCall(talkRoom);
        if (call != null) {
            if (call.getState() == Call.State.Pausing ||
                    call.getState() == Call.State.Paused ||
                    call.getState() == Call.State.PausedByRemote) {
                LinphoneManager.getLcIfManagerNotDestroyedOrNull().resumeCall(call);
            }
        }
    }

    /**
     * 暂停对讲
     */
    public void pauseTalkCall(String talkRoom) {
        Call call = lookTalkCall(talkRoom);
        if (call != null) {
            LinphoneManager.getLcIfManagerNotDestroyedOrNull().pauseCall(call);
        }
    }

    /**
     * 查找对讲的LinphoneCall
     * @param talkRoom
     * @return
     */
    public Call lookTalkCall(String talkRoom) {

        Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
        if (core != null) {
            Call[] calls = core.getCalls();
            for (Call call : calls) {
                if (call.getRemoteAddress() != null) {
                    if (TextUtils.equals(call.getRemoteAddress().getUsername(), talkRoom)) {
                        return call;
                    }
                }
            }
        }
        return null;
    }
}
